
var fun_aes = require('aes.js')
var util = require('util.js')
var app = getApp();

var requestHandler = {
    params: {},
    url: '',
    success: function (res) {
        // success
    },
    fail: function (fail) {
        // fail
    },
}



//GET请求
function GET(requestHandler) {
    request('GET', requestHandler)
}
//POST请求
function POST(requestHandler) {
    request('POST', requestHandler)
}

function request(method, requestHandler) {
    var params = requestHandler.params;
    var url = requestHandler.url;
    // console.log(requestHandler.params);
    
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    var currentTime = 'px2015' + ',' + timestamp;
    //   var currentTime = 'px2015,1500533533';
    var auth = Encrypt(currentTime);

    var app = getApp();
    var app_token = app.globalData.accountInfo.token;
    var app_data = '{"app_token":""}';
    // 是否是登录接口
    var isLogin = url.indexOf("login");
    // 获取验证码
    var isVerify = url.indexOf("captcha/get");
    // 忘记密码
    var isForGetPwd = url.indexOf("shopuser/modifyPasswd");

    if (isLogin >= 0 || isVerify >= 0 || isForGetPwd>=0) {//不包含 == -1 包含>=0

    }else{
        app_data = '{"app_token":"' + app_token + '"}'

    }
    // console.log(params);
    wx.request({
        url: url,
        data: params,
        method: method,
        header: {
            'app_id': 'px2015',
            'app_auth': auth,
            'app_auth_iv': 'p0i0a0o0x0i0a0ng',
            'app_data': app_data,
            'content-type': "application/x-www-form-urlencoded"
        },
        success: function (res) {

          if (res.data.code == '9002' || res.data.code == '9001'){
            app.globalData.accountInfo = {};
            wx.reLaunch({
              url: '../index/index',
            })
            return;
          }


            requestHandler.success(res)
        },
        fail: function (fail) {
            requestHandler.fail(fail)
        }
    })
}
// AES加密
function Encrypt(word) {

    var key = fun_aes.CryptoJS.enc.Utf8.parse("000piaoxiang0000");
    var iv = fun_aes.CryptoJS.enc.Utf8.parse("p0i0a0o0x0i0a0ng");
    var srcs = fun_aes.CryptoJS.enc.Utf8.parse(word);
    var encrypted = fun_aes.CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: fun_aes.CryptoJS.mode.CBC, padding: fun_aes.CryptoJS.pad.ZeroPadding });
    return encrypted.toString();

}

module.exports = {
    GET: GET,
    POST: POST
}
